package com.atguigu.tms.mock.task;


import com.atguigu.mock.util.MapUtil;
import com.atguigu.mock.util.MyDateUtil;
import com.atguigu.mock.util.RandomNum;
import com.atguigu.tms.mock.bean.*;
import com.atguigu.tms.mock.config.AppConfig;
import com.atguigu.tms.mock.constant.TmsConstant;
import com.atguigu.tms.mock.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.atguigu.tms.mock.constant.TmsConstant.TASK_TYPE_TRANSPORT;


@Component
@Slf4j
public class SortingMockTask {



    @Autowired
    BaseComplexService baseComplexService;

    @Autowired
    OrderInfoService orderInfoService;


    @Autowired
    EmployeeInfoService employeeInfoService;

    @Autowired
    ExpressCourierService expressCourierService;

    @Autowired
    ExpressCourierComplexService expressCourierComplexService;


    @Autowired
    ExpressTaskCollectService expressTaskCollectService;

    @Autowired
    OrderOrgBoundService orderOrgBoundService;

    @Autowired
    LineBaseShiftService lineBaseShiftService;

    @Autowired
    TransportPlanLineDetailService transportPlanLineDetailService;

    @Autowired
    TransportTaskService transportTaskService;

    @Autowired
    TransportTaskDetailService transportTaskDetailService;

    @Autowired
    SorterInfoService sorterInfoService;

    @Autowired
    OrderTraceLogService orderTraceLogService;


  @Scheduled(cron = "0/15 * * * * ?")
  public  void executeTask(){
     log.info("检查快递任务....");
    //  List<OrderInfo> orderInfoPaidList = getOrderInfoPaidList();


  }




  public void mainBatchTask(){


      expressCourierService.loadCache();


      for (int i = 0; i < AppConfig.collect_hours.length; i++) {
          String collectHour = AppConfig.collect_hours[0];
          String commitHour = AppConfig.commit_hours[0];
          log.info("--- 揽货快递 开始 ，时间："+collectHour+"   ---");
         // doCollectCommit(   collectHour,  commitHour );
          log.info("--- 揽货快递 完成 ，时间："+commitHour+"   ---");
      }


  }


    // 检查在站点中入站状态的订单
    // 找到每个订单下一个路线
    //通过路线找到下一个班次
    //根据班次和订单号 生成运输任务和运输任务明细
  public void doTask(Date curDate,Integer curHour,Integer shiftClock){

      List<OrderOrgBound> orderOrgBoundList = orderOrgBoundService.getOrderOrgBoundList(TmsConstant.BOUND_STATUS_IN);
      Map<Long ,List<Long>> lineOrderMap=new HashMap<>(); //地区和下一次运输清单
      for (OrderOrgBound orderOrgBound : orderOrgBoundList) {

          TransportPlanLineDetail nextTransportPlanLineDetail = transportPlanLineDetailService.getNextTransportPlanLineDetail(orderOrgBound.getOrderId(), orderOrgBound.getOrgId());
          if(nextTransportPlanLineDetail!=null){ //发现有下一步运输计划
              List<Long> orderIdList = lineOrderMap.get(nextTransportPlanLineDetail.getLineBaseId());
              if(orderIdList==null){
                  orderIdList  = new ArrayList<>();
                  orderIdList.add(orderOrgBound.getOrderId());

              }else{
                  orderIdList.add(orderOrgBound.getOrderId());
              }
              lineOrderMap.put(nextTransportPlanLineDetail.getLineBaseId(),orderIdList);
          }
      }

      //根据 班次生成任务，把订单匹配到任务中  路线下一次运输清单 生成运输任务
      List<LineBaseShift> nextShiftList = lineBaseShiftService.getNextShiftList(shiftClock);

      List<Long> taskedOrderIds=new ArrayList<>();
      for (LineBaseShift lineBaseShift : nextShiftList) {

          List<Long> orderIds = lineOrderMap.get(lineBaseShift.getLineId());
          if(orderIds!=null){
              taskedOrderIds.addAll(orderIds);
          }
          transportTaskService.initTransportTask(lineBaseShift,orderIds,curDate);

      }


      List<OrderOrgBound> taskedOrderOrgBoundList=new ArrayList<>();
      for (OrderOrgBound orderOrgBound : orderOrgBoundList) {
          if(taskedOrderIds.contains( orderOrgBound.getOrderId())){
              orderOrgBound.setStatus(TmsConstant.BOUND_STATUS_TRANS_TASKED);
              taskedOrderOrgBoundList.add(orderOrgBound);
          }
      }
      orderOrgBoundService.saveOrUpdateBatch(orderOrgBoundList,1000,true);




  }

    // 检查 order_bound 中tasked状态的订单
    // 找到每个org的分拣员
    // 找到订单对应运输任务的明细
    //  改变order_bound 的状态和 运输任务的明细签上sorter id
  public void doSort(Date curDate ,Integer intervalMinute ){

      Date endSortDate=DateUtils.addMinutes(curDate,intervalMinute);

     List<OrderOrgBound> orderOrgBoundList = orderOrgBoundService.getOrderOrgBoundList(TmsConstant.BOUND_STATUS_TRANS_TASKED);
      log.warn("待分拣 : 共 {} 件",orderOrgBoundList.size() );

      //整理为以org为单位的集合
      Map<Long,List<Long>>  orgOrderMap=new HashMap<>();
      Map<Long,Date>  orgSortDateMap=new HashMap<>();

      //待分拣任务
      List<TransportTaskDetail> taskDetailToSortList =
              transportTaskDetailService.list(new QueryWrapper<TransportTaskDetail>()
                      .isNull("sorter_emp_id")
                );
      Map<Long, TransportTaskDetail> orderIdTaskDetailMap = MapUtil.getIdMapFromList(taskDetailToSortList, "orderId");

      //分拣员列表
      List<SorterInfo> sorterInfoList = sorterInfoService.list();
      Map<Long, SorterInfo> sorterByOrgIdMap = MapUtil.getIdMapFromList(sorterInfoList, "orgId");

       Set<Long> transportTaskIdSet=new HashSet<>();
      for (OrderOrgBound orderOrgBound : orderOrgBoundList) {
          //获得分拣时间
          Date sortDate = orgSortDateMap.get(orderOrgBound.getOrgId());
          if(sortDate==null){
                 sortDate = curDate;
          }
          sortDate = DateUtils.addSeconds(sortDate, RandomNum.getRandInt(1, 10));

          if(sortDate.after(endSortDate)){
              break;
          }

          orgSortDateMap.put(orderOrgBound.getOrgId(),sortDate);

          //获得分拣员
          SorterInfo sorterInfo = sorterByOrgIdMap.get(orderOrgBound.getOrgId());

          //获得任务分拣明细
          TransportTaskDetail transportTaskDetail = orderIdTaskDetailMap.get(orderOrgBound.getOrderId());
          if(transportTaskDetail ==null){
              System.out.println(transportTaskDetail);
          }
          transportTaskDetail.setSorterEmpId(sorterInfo.getEmpId());
          transportTaskDetail.setUpdateTime(sortDate);

          orderOrgBound.setStatus(TmsConstant.BOUND_STATUS_SORTED);
          orderOrgBound.setSortTime(sortDate);
          orderOrgBound.setSorterEmpId(sorterInfo.getEmpId());


          transportTaskIdSet.add( transportTaskDetail.getTransportTaskId());


      }

      orderOrgBoundService.saveOrUpdateBatch(orderOrgBoundList,1000,true);


      transportTaskDetailService.saveOrUpdateBatch(taskDetailToSortList,1000,true);

      genOrderTraceLogSorted(  taskDetailToSortList  );

      List transportTaskSortedList = checkSortedTaskList(transportTaskIdSet, orgSortDateMap);

      transportTaskService.saveOrUpdateBatch(transportTaskSortedList,1000,true);


  }


  private List checkSortedTaskList(Set<Long > transportTaskIdSet,Map<Long,Date>  orgSortDateMap  ){
      List<TransportTask> transportTaskSortedList=new ArrayList<>();
      for (Long transportTaskId : transportTaskIdSet) {

          List<TransportTaskDetail> transportTaskDetailList = transportTaskDetailService.list(new QueryWrapper<TransportTaskDetail>().eq("transport_task_id", transportTaskId));

          boolean ifFinished=true;
          for (TransportTaskDetail transportTaskDetail : transportTaskDetailList) {
              if(transportTaskDetail.getSorterEmpId()==null){
                  ifFinished=false;
                  break;
              }
          }

          if(ifFinished){
              TransportTask transportTask = transportTaskService.getById(transportTaskId, true);
              Date sortEndDate = orgSortDateMap.get(transportTask.getStartOrgId());
              transportTask.setUpdateTime(sortEndDate);
              transportTask.setStatus(TmsConstant.TRANSPORT_TASK_STATUS_SORTED);
              transportTaskSortedList.add(transportTask);
          }


      }
      return  transportTaskSortedList;

  }


    private void genOrderTraceLogSorted(List<TransportTaskDetail>  taskDetailToSortedList  ) {
      List<OrderTraceLog> orderTraceLogList =new ArrayList<>();


        for (TransportTaskDetail transportTaskDetail : taskDetailToSortedList) {
            OrderTraceLog orderTraceLog = new OrderTraceLog();
            orderTraceLog.setOrderId(transportTaskDetail.getOrderId());

            orderTraceLog.setTraceDesc("分拣完成等待出发 "  );
            orderTraceLog.setCreateTime(transportTaskDetail.getUpdateTime());
            orderTraceLog.setCurTaskId(transportTaskDetail.getTransportTaskId());
            orderTraceLog.setChargeEmpId(transportTaskDetail.getSorterEmpId());
            orderTraceLog.setTaskType(TASK_TYPE_TRANSPORT);
            orderTraceLog.setIsDeleted("0");

            orderTraceLogList.add(orderTraceLog);
        }
        orderTraceLogService.saveOrUpdateBatch(orderTraceLogList,1000,true);
    }

}
